package org.qdog.pk.pkscrape.controller;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.namespace.QName;
import javax.xml.xpath.*;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @since 08/2011
 */
class XPathHelper {
  private static final Logger log = Logger.getLogger(XPathHelper.class);

  public static Collection<String> extractHyperlinks(final Document doc, final String startingXpath)
        throws XPathExpressionException {

    log.debug("Extracting hyperlinks from child elements of " + startingXpath);
    NodeList nodes = (NodeList) xPath(doc, startingXpath + "//a/@href", XPathConstants.NODESET);

    log.debug(nodes.getLength() + " hyperlinks found");
    Collection<String> hyperlinks = new ArrayList<String>(nodes.getLength());

    for (int i = 0; i < nodes.getLength(); i++) {
      String href = nodes.item(i).getNodeValue();
      if (StringUtils.isNotBlank(href)) {
        hyperlinks.add(nodes.item(i).getNodeValue());
      }
    }

    return hyperlinks;
  }

  public static String textByIdList(Node node, String... id) throws XPathExpressionException {
    String result = null;
    for (String identifier : id) {
      result = xPathAsString(node, "//*[@id='" + identifier + "']/text()");
      if (result != null) {
        result = StringUtils.trim(result);
        break;
      }
    }
    return result;
  }

  public static String hrefByIdList(Node node, String... id) throws XPathExpressionException {
    String result = null;
    for (String identifier : id) {
      result = xPathAsString(node, "//*[@id='" + identifier + "']/@href");
      if (result != null) {
        break;
      }
    }
    return result;
  }

  public static String xPathAsString(Node node, String expression) throws XPathExpressionException {
    return (String) xPath(node, expression, XPathConstants.STRING);
  }

  private static Object xPath(Node node, String expression, QName returnType) throws XPathExpressionException {
    // Create a XPathFactory
    XPathFactory xFactory = XPathFactory.newInstance();

    // Create a XPath object
    XPath xpath = xFactory.newXPath();

    // Compile the XPath expression
    XPathExpression expr = xpath.compile(expression);
    return expr.evaluate(node, returnType);
  }
}
